﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace ExportFethionHistory
{
    class CConfig
    {
        private string _FileName;
        private XmlDocument _xmlDocument;

        public string FileName
        {
            get
            {
                return _FileName;
            }
            set
            {
                _FileName = value;
            }
        }

        // return :
        // true : the file exist and we open it 
        // false : the file doesn't exist and we create it 
        public bool Open()
        {
            try
            {
                _xmlDocument.Load(_FileName);
            }
            catch (System.IO.FileNotFoundException)
            {
                //if file is not found, create a new xml file
                XmlTextWriter xmlWriter = new XmlTextWriter(_FileName, System.Text.Encoding.UTF8);
                xmlWriter.Formatting = Formatting.Indented;
                xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
                xmlWriter.WriteStartElement("Root");
                //If WriteProcessingInstruction is used as above,
                //Do not use WriteEndElement() here
                //xmlWriter.WriteEndElement();
                //it will cause the <Root></Root> to be <Root />
                xmlWriter.Close();
                _xmlDocument.Load(_FileName);
                return false;
            }
            return true;
        }

        public CConfig(string strFileName)
        {
            FileName = strFileName;
            _xmlDocument = new XmlDocument();
            this.Open();
        }

        ~CConfig()
        {
            Save();
        }

        public void Save()
        {
            _xmlDocument.Save(_FileName);
        }

        public string Get(string strName)
        {
            XmlNode node = _xmlDocument.SelectSingleNode("Root").SelectSingleNode(strName);
            if (node == null)
            {
                return "";
            }
            else
            {
                return node.InnerText;
            }
        }

        public void Set(string strName, string strValue)
        {
            XmlNode root = _xmlDocument.SelectSingleNode("Root");
            XmlNode node = root.SelectSingleNode(strName);

            if (node != null)
            {
                node.InnerText = strValue;
            }
            else
            {
                XmlElement elem = _xmlDocument.CreateElement(strName);
                elem.InnerText = strValue;
                root.AppendChild(elem);
            }
        }
    }
}